import { api } from "@/api";
import router from "@/router";
import { convertMessageTextToRich, valueToType } from "@/utils";
import dayjs from "dayjs";
import { defineStore } from "pinia";
import useContactsStore from "./contacts";
import { isAppEnv, notify } from "@/uni";

const ACCESS_TOKEN_STORAGE_KEY = 'im-app-token'
const USER_INFO_STORAGE_KEY = 'im-app-user-info'
const LAST_UNREAD_STORAGE_KEY = 'im-app-last-unread'
export const APP_KEY = '8B37E8QEMxfvfVI19ZHXy3Rbu03l2vSM'
export const APP_SECRET = 'wC1cRxQZt3kyfTNHIFJKVngJOM24tPtcHpIfiQDt0UZO3IVfxOzWYiQAh0EUEEIZ'

export const useAppStore = defineStore('app', {
  state: () => {
    const state = {
      playInited: false,
      lastUnread: 0,
      sessionList: [],
      accessToken: '',
      token: '',
      title: 'IM',
      userInfo: {
        username: '',
        nickname: '',
        avatar: '',
        mobile: '',
        invitationCode: ''
      },
      balance: 0
    }

    const accessToken = localStorage.getItem(ACCESS_TOKEN_STORAGE_KEY)
    if (accessToken) state.accessToken = accessToken
    const userInfo = localStorage.getItem(USER_INFO_STORAGE_KEY)
    if (userInfo) state.userInfo = JSON.parse(userInfo)
    const lastUnread = localStorage.getItem(LAST_UNREAD_STORAGE_KEY)
    if (lastUnread) state.lastUnread = parseInt(lastUnread)

    return state
  },
  getters: {
    hasLogged: (state) => state.accessToken !== '',
    unread: (state) => state.sessionList.map(item => item.unread).reduce((a, b) => a + b, 0),
    mobileMosaic: (state) => state.userInfo.mobile?.replace(/(\d{3})\d{3}(\d{5})/, '$1****$2'),
    contactsStore: () => useContactsStore(),
  },
  actions: {
    async refreshSessionList(notify = true) {
      const { data } = await api.chat.sessionList()

      if (!Array.isArray(data)) return
      const isEmpty = this.sessionList.length === 0

      this.sessionList = data.map(item => ({
        ...item,
        lastMsg: item.lastMsg?.map(item => ({
          ...item,
          content_type: valueToType(item.content_type),
          msg: convertMessageTextToRich(item.msg),
          update_time: dayjs.unix(item.update_time).format('HH:mm')
        })) ?? [],
      }))

      if (notify && this.unread > this.lastUnread && !isEmpty) {
        this.playNotice()
      }

      this.setLastUnread(this.unread)
    },
    async refreshBalance() {
      const { balance } = await api.wallet.balance()
      this.balance = balance
    },
    setToken(token) {
      this.accessToken = token
      localStorage.setItem(ACCESS_TOKEN_STORAGE_KEY, token)
    },
    setUserInfo(userInfo) {
      Object.assign(this.userInfo, userInfo)
      localStorage.setItem(USER_INFO_STORAGE_KEY, JSON.stringify(this.userInfo))
    },
    setLastUnread(lastUnread) {
      this.lastUnread = lastUnread
      localStorage.setItem(LAST_UNREAD_STORAGE_KEY, lastUnread)
    },
    async logout() {
      api.logout({ userName: this.accessToken })
      this.accessToken = ''
      localStorage.removeItem(ACCESS_TOKEN_STORAGE_KEY)
      localStorage.removeItem(USER_INFO_STORAGE_KEY)
      this.$reset()
      this.contactsStore.reset()
      router.push({ name: 'Login' })
    },
    async playNotice(muted) {
      if (this.playInited && muted) return

      if (await isAppEnv()) {
        if (muted) {
          this.playInited = true
          return
        }
        notify()
      } else {
        /** @type {HTMLAudioElement} */
        const audio = document.getElementById('notice')
        audio.loop = false
        audio.volume = muted ? 0 : 1
        audio.currentTime = 0
        audio.play()
        if (muted) {
          this.playInited = true
          return
        }

        const notification = () => new Notification("您有新的消息");

        if (!("Notification" in window)) {
          // 当前浏览器不支持桌面通知
        } else if (Notification.permission === "granted") {
          // 检查是否已授予通知权限；如果是的话，创建一个通知
          notification()
          // …
        } else if (Notification.permission !== "denied") {
          // 我们需要征求用户的许可
          Notification.requestPermission().then((permission) => {
            // 如果用户接受，我们就创建一个通知
            if (permission === "granted") {
              notification()
            }
          });
        }
      }
    }
  }
})

export function setNavbarTitle(title) {
  useAppStore().title = title
}
